axios.defaults.baseURL = "/";
axios.defaults.timeout = 2000;

// 请求拦截器
axios.interceptors.request.use(
  config => {
    const token = sessionStorage.getItem("token");
    if (token) {
      config.headers['authorization'] = `Bearer ${token}`;
    }
    return config;
  },
  error => Promise.reject(error)
);

// 响应拦截器
axios.interceptors.response.use(
  response => response.data,
  error => {
    const { response } = error;

    if (!response) {
      window.message.error('网络连接失败');
      return Promise.reject(error);
    }

    if (response.status === 401) {
      sessionStorage.clear();
      location.href = "/login";
    } else {
      const errorMsg = response.data?.message || `请求失败: ${response.status}`;
      window.message.error(errorMsg);
    }

    return Promise.reject(error);
  }
);